package com.nwork.qingmanhua.imagedown;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.text.TextUtils;

import com.nwork.qingmanhua.utils.CommonUtils;

import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * 将资源缓存到硬盘中
 */
public class DiskMemoryCache implements IMemoryCache {

    /**
     * 从本地文件中取出一个BitMap
     *
     * @param url bitMap的URL
     * @return
     */
    @Override
    public Bitmap get(String url) {
        if (TextUtils.isEmpty(url)) {
            return null;
        }

        // 从sd卡拿图片
        byte[] data = ImgFileManager.getBitmap(url);
        if (data != null && data.length > 0) {
            return BitmapFactory.decodeByteArray(data, 0, data.length);
        }

        data = downloadBitmap(url);
        if (data != null && data.length > 0) {
            put(url, data);
            return BitmapFactory.decodeByteArray(data, 0, data.length);
        }

        return null;
    }

    @Override
    public void put(String url, Bitmap bitmap) {
    }

    /**
     * 将得到的数据写入文件缓存中
     *
     * @param url  得到数据的url
     * @param data 得到的数据
     */
    public void put(String url, byte[] data) {
        if (!TextUtils.isEmpty(url) && data != null) {
            ImgFileManager.saveBitmap(url, data);
        }
    }

    /**
     * 清除指定的缓存 ！！！！未实现
     *
     * @param url
     */
    @Override
    public void remove(String url) {
    }

    /**
     * 清除所有的缓存 ！！！ 未实现
     */
    @Override
    public void clearAll() {
    }

    private byte[] downloadBitmap(String urlString) {
        HttpURLConnection conn = null;
        try {
            URL url = new URL(urlString);
            conn = (HttpURLConnection) url.openConnection();
            InputStream is = conn.getInputStream();
            if (is != null) {
                return CommonUtils.streamToByteArray(is);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (conn != null) {
                conn.disconnect();
            }
        }
        return null;
    }
}
